// 登录与注册
const express = require("express");
const router = express.Router();
const bcrypt = require("bcryptjs"); //加密用的插件
const gravatar = require("gravatar"); //全球公认头像插件
const jwt = require("jsonwebtoken"); //token插件
const passport = require("passport"); //express的兼容身份验证插件

const User = require("./../../models/User");
const keys = require("./../../config/keys");

const TOKEN_EFFECTIVE_TIME = 3600;  //token的有效时间(秒)

//接口测试
router.get("/test", (req, res) => {
  res.json({msg: "测试成功了哦"});
});

//注册业务处理
/**
 * $route POST请求 api/users/register
 * @desc 返回请求的json数据
 * @access Public
 * */
router.post("/register", (req, res) => {
  // res.json({msg: "你将要注册用户哦"});
  // console.log(req.body);
  // 查询数据库中是否有该邮箱
  User.findOne({email: req.body.email})
    .then((user) => {
      if(user){
        return res.status(400).json("邮箱已被注册！");
      }else{
        /**
         * 头像链接：
         * s是size(大小)
         * r是rating(等级)
         * d是default(默认)
         * */
        const avatar = gravatar.url(req.body.email, {s: '200', r: 'pg', d: 'mm'});

        const newUser = new User({
          name: req.body.name,
          email: req.body.email,
          avatar,
          identity: req.body.identity,
          password: req.body.password
        });
        //加密密码
        bcrypt.genSalt(10, function(err, salt) {
          bcrypt.hash(newUser.password, salt, (err, hash) => {
            // Store hash in your password DB.
            if(err) throw err;
            newUser.password = hash; //转成哈希值
            //保存
            newUser.save()
              .then(user => res.json(user))
              .catch(err => console.log(err));
          });
        });
      }
    })
});

//登录业务处理
/**
 * $route POST请求 api/users/login
 * @desc 返回token
 * @access Public
 * */
router.post("/login", (req, res) => {
  const email = req.body.email;
  const password = req.body.password;
  //查询数据库
  User.findOne({email})
    .then(user => {
      if(!user){
        return res.status(404).json("用户不存在！");
      }
      //密码匹配
      bcrypt.compare(password, user.password)
        .then(isMatch => {
          if (isMatch){
            const rule = {
              id: user.id,
              name: user.name,
              identity: user.identity,
              email: user.email
            };
            const avatar = user.avatar;
            // jwt.sign(规则,名字,过期时间,回调函数)
            // token: "Bearer "+token 这里token名得是Bearer加空格
            jwt.sign(rule, keys.secretOrKey, {expiresIn: TOKEN_EFFECTIVE_TIME}, (err, token) => {
              if(err) throw err;
              // res.json({success: true, token: "Bearer "+token});
              res.json({
                success: true,
                info: {
                  token: "Bearer "+token,
                  avatar: avatar
                }
              });
            });
            // res.json({msg: "匹配成功！"});
          }else{
            res.status(400).json("密码错误！");
          }
        })
    })
});

//验证（token）
/**
 * $route GET请求 api/users/current
 * @desc 返回current user
 * @access Private
 * */
router.get("/current", passport.authenticate("jwt", {session: false}), (req, res) => {
  // res.json({msg: "验证成功！"});
  // res.json(req.user);
  res.json({
    id: req.user.id,
    name: req.user.name,
    email: req.user.email,
    identity: req.user.identity
  });
});

//获取用户资料(不包括密码)
/**
 * $route POST请求 api/users/edit
 * @desc 返回请求的json数据
 * @access Private
 * */
router.get("/info/:id", passport.authenticate("jwt", {session: false}), (req, res) => {
  User.findOne({_id: req.params.id})
    .then(user => {
      if(!user) {
        return res.status(404).json("没有该用户");
      }
      //不把密码提交出去，赋空值(其实加密后是一串哈希值，哈希加密是不可逆的，只能后台匹配)
      user.password = '';
      res.json(user);
    })
    .catch(err => res.status(404).json(err));
});

//编辑修改用户资料
/**
 * $route POST请求 api/users/edit
 * @desc 返回请求的json数据
 * @access Private
 * */
router.post("/info/edit/:id", passport.authenticate("jwt", {session: false}), (req, res) => {
  const userInfo = {};
  if (req.body.name) userInfo.name = req.body.name;
  if (req.body.email) userInfo.email = req.body.email;
  if (req.body.newPassword) userInfo.password = req.body.newPassword;
  if (req.body.avatar) userInfo.avatar = req.body.avatar;

  if (req.body.oldPassword) {
    let oldPassword = req.body.oldPassword;
    User.findOne({_id: req.params.id})
      .then(user => {
        if(!user){
          return res.status(404).json("用户不存在！");
        }
        //旧密码验证/匹配:
        bcrypt.compare(oldPassword, user.password)
          .then(isMatch => {
            if(isMatch){
              //加密密码
              bcrypt.genSalt(10, function(err, salt) {
                bcrypt.hash(userInfo.password, salt, (err, hash) => {
                  // Store hash in your password DB.
                  if(err) throw err;
                  userInfo.password = hash; //转成哈希值
                  //更新用户信息
                  User.findOneAndUpdate(
                    {_id: req.params.id},
                    {$set: userInfo},
                    {new: true}
                  ).then(user => {
                    res.json(user);
                  });
                });
              });

            }else{
              res.status(400).json("旧密码错误");
            }
          })

      })
      .catch(err => {
        res.status(404).json("修改失败");
        console.log(err);
      })

  }

});


module.exports = router;